﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using IFDB.Models.Contexts;
using IFDB.ResourceLibrary;
using IFDB.Services.Foundation.Sites.Sources;

namespace IFDB.Services.Application.Sites.Sources
{
    public class Soccerbase : BaseImport
    {
        public Soccerbase()
            : base(Site.Soccerbase)
        {
        }

        private IFDBContext db = new IFDBContext();

        #region GetTeamLookups
        public void GetTeamLookups()
        {
            StreamWriter log = new StreamWriter(@"P:\logs\IFDB_Soccerbase_Team_Lookup.csv", true);

            string url = string.Format("http://www.soccerbase.com/teams/home.sd");

            HtmlDocument document = GetHtmlDocument(url);

            // <a href="/teams/team.sd?team_id=142&amp;comp_id=1" onclick="scorecards.sendSpecificDesc('team_link',&quot;Arsenal&quot;);">Arsenal</a>

            var teamQuery = from a in document.DocumentNode.Descendants("a")
                            where a.Attributes["href"].Value.IndexOf("/teams/team.sd?team_id=") != -1
                            select a;

            foreach (var a in teamQuery)
            {
                string teamName = a.Attributes["onclick"].Value.GetTextBetween("'team_link',&quot;", "&quot;)");
                string espnId = a.Attributes["href"].Value.GetTextBetween("/teams/team.sd?team_id=", "&");

                log.WriteLine(string.Format("{0}, {1}", teamName, espnId));
            }

            log.Close();
        }
        #endregion

        public void ImportMatches(DateTime viewDate)
        {
            //http://www.soccerbase.com/matches/results.sd?date=2013-03-24

            string url = string.Format("http://www.soccerbase.com/matches/results.sd?date=" + viewDate.ToString("yyyy-MM-dd"));

            HtmlDocument document = GetHtmlDocument(url);

            var tableQuery = from table in document.DocumentNode.Descendants("table")
                             where table.Attributes["class"].Value == "soccerGrid listWithCards"
                             select table;

            int competitionId = -1;
            string team1Id = string.Empty;
            Guid team1Guid;
            short team1FT = 0;
            string team2Id = string.Empty;
            Guid team2Guid;
            short team2FT = 0;

            foreach (var row in tableQuery.First().Descendants("tr"))
            {
                if (row.Descendants("th").Count() > 0)
                {
                    competitionId = Convert.ToInt32(row.Descendants("a").First().Attributes["href"].Value.GetTextAfter("/tournaments/tournament.sd?comp_id="));
                    //string competitionName = row.Descendants("a").First().InnerText.Trim();
                }

                if (IsCompetitionValid(competitionId))
                {
                    if (row.Attributes["class"] != null && row.Attributes["class"].Value == "match")
                    {
                        foreach (var cell in row.Descendants("td"))
                        {
                            if (cell.Attributes["class"] != null)
                            {
                                switch (cell.Attributes["class"].Value)
                                {
                                    case "team homeTeam":
                                        team1Id = cell.SelectSingleNode("a").Attributes["href"].Value.GetTextAfter("/teams/team.sd?team_id=");
                                        team1Guid = db.LookupTeams.Single(t => t.LookupId == team1Id).TeamId;
                                        break;

                                    case "team awayTeam":
                                        team2Id = cell.SelectSingleNode("a").Attributes["href"].Value.GetTextAfter("/teams/team.sd?team_id=");
                                        team2Guid = db.LookupTeams.Single(t => t.LookupId == team2Id).TeamId;
                                        break;

                                    case "score":
                                        team1FT = Convert.ToInt16(cell.SelectSingleNode("a").SelectNodes("em")[0].InnerText);
                                        team2FT = Convert.ToInt16(cell.SelectSingleNode("a").SelectNodes("em")[1].InnerText);
                                        break;
                                }
                            }

                            // <td class="team homeTeam"> <a href="/teams/team.sd?team_id=2598" title="Go to Tranmere team page">Tranmere</a> </td>
                            

                            //team2Id = row.Descendants("td").Where(t => t.Attributes["class"].Value == "team awayTeam").First().SelectSingleNode("a").InnerText.GetTextAfter("/teams/team.sd?team_id=");
                            //team2Guid = db.LookupTeams.Single(t => t.LookupId == team2Id).TeamId;

                            // <td class="score"> <a href="#" class="vs" title="View Match info"><em>3</em>&nbsp;-&nbsp;<em>1</em></a> </td>
                            //team1FT = Convert.ToInt16(row.Descendants("td").Where(t => t.Attributes["class"].Value == "score").First().SelectSingleNode("a").SelectNodes("em")[0].InnerText);
                            //team2FT = Convert.ToInt16(row.Descendants("td").Where(t => t.Attributes["class"].Value == "score").First().SelectSingleNode("a").SelectNodes("em")[1].InnerText);
                        }
                    }
                }
            }
        }

        private bool IsCompetitionValid(int competitionId)
        {
            switch (competitionId)
            {
                case 3:
                    return true;

                default:
                    return false;
            }
        }
    }
}
